/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "../core/core.h"
#include <Windows.h>
#include <conio.h>
#include "../interfaces/int_engine.h"
#include "console.h"

/*-----------------------------------------------------------------------------
	Main :
-----------------------------------------------------------------------------*/

void SetLogCB(void);

class EApp : public ICoreApp {
	public:
		virtual void	Init		( const EArgs &args );
		virtual void	Shutdown	( void );
		virtual void	Frame		( uint dtime );
		
	protected:
		static EApp	*self;
	
		HardRef<EConsole>	console;
		
		static int	openConsole	( lua_State *L ) 
		{
			LUA_INTERFACE(L);
			
			self->console->Activate(true);
			
			return 0;
		}
	
		static int	setGame		( lua_State *L ) 
		{
			LUA_INTERFACE(L);
			
			if (lua_isnil(L, 1)) {
				Config()->SaveConfig();
				Linker()->LinkGame( NULL );
				FileSystem()->changeDirectory( ".." );
				return 0;
			}
			
			EString	game	=	lua.RequireString( 1, "game directory name" );
			
			Config()->SaveConfig();
			Linker()->LinkGame( NULL );

			FileSystem()->changeDirectory( game.CStr() );

			LOGF("selected game : %s", game.CStr());
			
			Config()->LoadConfig();
			Linker()->LinkDLLGame( va("../%s/game.dll", game.CStr()) );
			
			return 0;
		}
	};
	

EApp *EApp::self	=	NULL;


//
//	EApp::Init
//
void EApp::Init( const EArgs &args )
{
	self	=	this;
	LUA_STACK_GUARD(CoreLua());

	LOGF("Engine version : %s", CoreVersion());
	LOGF("Command line   : %s", System()->GetCmdLine());
	
	CoreExecuteString("package.path  = './?.lua;./lua/?.lua'");
	CoreExecuteString("package.cpath = ''");

	int _game;
	
	EString	path_dir;
	EString	path_dll;

	FileSystem()->changeDirectory("..");

	if (/*args.CheckParam("-ship", &_game)*/ false) {
	
		path_dir	=	"game_ship";
		path_dll	=	"game_ship.dll";

		FileSystem()->changeDirectory(path_dir.CStr());
		
		Config()->LoadConfig();
		
		Linker()->LinkDLLRenderSystem	( "rend_d3d9.dll" );
		Linker()->LinkDLLSoundSystem	( "sound_fmod.dll" );
		Linker()->LinkDLLPhysics		( "phys_bt.dll" );
		Linker()->LinkDLLGame			( path_dll.CStr() );

		InputSystem()->SetTargetWindow( rs()->GetWindowHandle() );
		InputSystem()->SetInputMode( IN_KB_SCAN );
		
		CoreExecuteFile( "loader.lua" );
		
	} else {
	
		EString		game_dir	=	"game_2048";
		
		if (args.CheckParam("-game", &_game)) {
			game_dir = args.Argv(_game+1);
		}
		
		FileSystem()->changeDirectory(game_dir.CStr());
		
		Config()->LoadConfig();
		
		Linker()->LinkDLLRenderSystem	( "rend_d3d9.dll" );
		Linker()->LinkDLLSoundSystem	( "sound_fmod.dll" );
		Linker()->LinkDLLPhysics		( "phys_bt.dll" );

		LOGF("selected game : %s", game_dir.CStr());
		Linker()->LinkDLLGame			( va("../%s/game.dll", game_dir.CStr()) );

		InputSystem()->SetTargetWindow( rs()->GetWindowHandle() );
	}


	console	=	new EConsole();

	LUALIB_DECLARE	("engine")
	LUALIB_METHOD	( setGame )
	LUALIB_METHOD	( openConsole )
	LUALIB_REGISTER	( CoreLua() )
}


//
//	EApp::Shutdown
//
void EApp::Shutdown( void )
{
	console	=	NULL;

	LUA_STACK_GUARD(CoreLua());

	InputSystem()->SetTargetWindow( NULL );

	Linker()->LinkGame			( NULL );
	Linker()->LinkPhysics		( NULL );
	Linker()->LinkSoundSystem	( NULL );
	Linker()->LinkRenderSystem	( NULL );

	Config()->SaveConfig();

	FileSystem()->changeDirectory(NULL);
}


//
//	EApp::Frame
//
void EApp::Frame( uint dtime )
{
	//	process input :	
	ss()->Frame();
	InputSystem()->ProcessInput();
	
	//	begin rs frame :	
	if (rs()->BeginFrame()) {
	
		bool full_con = false;
		
		//	run game if loaded :
		if (game()) {
			full_con = true;
			game()->Frame( dtime );
		} else {
			console->Activate(true);
		}

		//	run physics :		
		phys()->RunSimulation( dtime );
		phys()->DebugRender( rs()->GetDVScene() );
		
		DEBUG_STRING("fps : %5.2g", 1000.0f / dtime );
		
		rs()->RenderFrame();
		
		console->Draw(full_con, dtime);
		
		rs()->EndFrame();
	}
	
	
	CoreIncFrameCount();
}


/*-----------------------------------------------------------------------------
	Entry point :
-----------------------------------------------------------------------------*/

//
//	main
//
int main( int argc, const char **argv)
{
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	//_CrtSetBreakAlloc(17865);

	system("cls");
	SetLogCB();
	
	EApp	app;

	bool r = CoreRunApp	( &app );
	
	if (!r) {
		LOGF("");
		LOGF("An error has occured, return 1");
		return 1;
	}
	
	Linker()->UnlinkAll();
	LOGF("All right, return 0");
	return 0;
}


int __stdcall WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )
{
	return main(0, NULL);
}

